package com.msl.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.msl.MslApp;
import com.msl.R;
import com.msl.adapter.MainAdapter;
import com.msl.base.BaseActivity;
import com.msl.bean.AbDcodeBean;
import com.msl.bean.AbUserBean;
import com.msl.dialog.ChooseDialog;
import com.msl.entity.CodeInfo;
import com.msl.entity.CodeInfoControl;
import com.msl.service.UpdateCodeService;
import com.msl.tool.ToastUtils;
import com.shelwee.update.UpdateHelper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends BaseActivity {

    private String tag = "MainActivity";
    @Bind(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.gridview)
    GridView gridview;
    OkHttpClient client1;
    AbUserBean.DataBean bean=null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        UpdateHelper updateHelper = new UpdateHelper.Builder(this)
                .checkUrl(MslApp.sSharedPreferences.getString(MslApp.addk, "") +
                        "/pda/APPSoftUpdate.ashx" +
                        "?cid=" + MslApp.sSharedPreferences.getString(MslApp.cidk, ""),"com.msl")
                .isAutoInstall(true) //设置为false需在下载完手动点击安装;默认值为true，下载后自动安装。
                .build();
        updateHelper.check();
        tvTitle.setText("主页");
        bean = (AbUserBean.DataBean)getIntent().getSerializableExtra(MslApp.mainicons);
        if(bean==null || bean.getList()==null||bean.getList().size()==0)
        {
            ToastUtils.showSingleToast(MainActivity.this,"当前账号未配置功能项");
            return;
        }
        MainAdapter mainAdapter = new MainAdapter(this,bean.getList());
        gridview.setAdapter(mainAdapter);
        client1 = new OkHttpClient.Builder()
                .retryOnConnectionFailure(false)
                .connectTimeout(5, TimeUnit.SECONDS)
                .build();

        //每次上传本地代码
        List<CodeInfo> list = CodeInfoControl.query();
        for (int i = 0; i < list.size(); i++) {
            CodeInfo cii = list.get(i);
            ArrayList<String> ci = new ArrayList<String>();
            ci.add(cii.getBillChangeType()); //setBillChangeType
            ci.add(cii.getBillcode()); //setBillcode
            ci.add(cii.getCid());//setCid
            ci.add(cii.getCode());//setCode
            ci.add(cii.getCodeType());//setCodeType
            ci.add(cii.getManualNums());//setManualNums
            ci.add(cii.getProductID());//setProductID
            ci.add(cii.getStoreID());//setStoreID
            ci.add(cii.getStoreInfo());//setStoreInfo
            ci.add(cii.getStoreOtherInfo());//setStoreOtherInfo
            ci.add(cii.getSubBillCode());//setSubBillCode
            ci.add(cii.getTransactionCode());//setTransactionCode
            ci.add(cii.getUserID());//setUserID
            ci.add(cii.getId() + "");
            updatecode(MslApp.url + "?action=UpdateCodes_Deatil&cid=" + cii.getCid()
                            + "&userID=" + cii.getUserID()
                            + "&storeID=" + cii.getStoreID()
                            + "&billcode=" + cii.getBillcode()
                            + "&productID=" + cii.getProductID()
                            + "&codeType=" + cii.getCodeType()
                            + "&codes=" + cii.getCode()
                            + "&manualNums=" + cii.getManualNums()
                            + "&subBillCode=" + cii.getSubBillCode()
                            + "&storeInfo=" + cii.getStoreInfo()
                            + "&storeOtherInfo=" + cii.getStoreInfo()
                            + "&billChangeType=" + cii.getBillChangeType()
                            + "&transactionCode=" + cii.getTransactionCode()
                    , ci
            );
        }
        Intent intentOne = new Intent(this, UpdateCodeService.class);
        startService(intentOne);
    }

    @OnClick({R.id.iv_title_left})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                ChooseDialog nDialog = new ChooseDialog(this, R.style.Dialog1, new ChooseDialog.PriorityListener() {
                    @Override
                    public void setActivityText() {
                        finish();
                    }
                });
                WindowManager.LayoutParams lp = nDialog.getWindow().getAttributes();
                lp.gravity = Gravity.CENTER;
                nDialog.setCanceledOnTouchOutside(false);
                nDialog.show();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            ChooseDialog nDialog = new ChooseDialog(this, R.style.Dialog1, new ChooseDialog.PriorityListener() {
                @Override
                public void setActivityText() {
                    finish();
                }
            });
            WindowManager.LayoutParams lp = nDialog.getWindow().getAttributes();
            lp.gravity = Gravity.CENTER;
            nDialog.setCanceledOnTouchOutside(false);
            nDialog.show();
        }
        return super.onKeyDown(keyCode, event);
    }

    void updatecode(String url, ArrayList<String> codeInfo) {
        final ArrayList<String> ci = codeInfo;
        try {
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            client1.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
//                    Message message = new Message();
//                    message.what = 1;
//                    Bundle bundle = new Bundle();
//                    bundle.putStringArrayList("ci", ci);
//                    message.setData(bundle);
//                    handler.sendMessage(message);
//                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {//回调的方法执行在子线程。
                        result = response.body().string();
                        AbDcodeBean ab = gson.fromJson(result, AbDcodeBean.class);
                        Message message = new Message();
                        message.what = 0;
                        Bundle bundle = new Bundle();
                        bundle.putStringArrayList("ci", ci);
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
//                    else {
//                        Log.e(tag, "获取数据失败了" + response.code());
//                        Message message = new Message();
//                        message.what = 2;
//                        Bundle bundle = new Bundle();
//                        bundle.putStringArrayList("ci", ci);
//                        message.setData(bundle);
//                        handler.sendMessage(message);
//                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    List<String> ci = msg.getData().getStringArrayList("ci");
                    CodeInfo codeInfo = new CodeInfo();
                    codeInfo.setBillChangeType(ci.get(0));
                    codeInfo.setBillcode(ci.get(1));
                    codeInfo.setCid(ci.get(2));
                    codeInfo.setCode(ci.get(3));
                    codeInfo.setCodeType(ci.get(4));
                    codeInfo.setManualNums(ci.get(5));
                    codeInfo.setProductID(ci.get(6));
                    codeInfo.setStoreID(ci.get(7));
                    codeInfo.setStoreInfo(ci.get(8));
                    codeInfo.setStoreOtherInfo(ci.get(9));
                    codeInfo.setSubBillCode(ci.get(10));
                    codeInfo.setTransactionCode(ci.get(11));
                    codeInfo.setUserID(ci.get(12));
                    codeInfo.setId(Long.parseLong(ci.get(13)));
                    CodeInfoControl.delete(codeInfo);
                    break;
                case 1:
                    break;
                case 2:
                    break;
            }
        }
    };
}
